package com.rapier.sso.server.controller;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.rapier.sso.core.config.redis.RedisClient;
import com.rapier.sso.server.constant.RapierServerConstant;
import com.rapier.sso.server.env.RapierSsoServerEnv;
import com.wf.captcha.SpecCaptcha;

/**
 * @author chenkw
 *
 */
@Controller
public class SsoServerAuthController {
	@Autowired
	private RedisClient redisClient;

	@Autowired
	private RapierSsoServerEnv ssoServerEnv;

	/**
	 * 验证码
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/captcha", method = RequestMethod.GET)
	public JSONObject captcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
		SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 5);
		String verCode = specCaptcha.text().toLowerCase();
		String key = UUID.randomUUID().toString();
		redisClient.set(RapierServerConstant.REDIS_SSO_USER_CAPTCHA_KEY + key, verCode,
				ssoServerEnv.getRedisLoginCaptchaExpireMinutes(), TimeUnit.MINUTES);
		// 将key和base64返回给前端
		JSONObject obj = new JSONObject();
		obj.put("key", key);
		obj.put("image", specCaptcha.toBase64());
		return obj;
	}
	
	@ResponseBody
	@RequestMapping(value = "/sms", method = RequestMethod.GET)
	public JSONObject sms(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String smsVal = "123456";
		String key = UUID.randomUUID().toString();
		redisClient.set(RapierServerConstant.REDIS_SSO_USER_SMS_KEY + key, smsVal,
				ssoServerEnv.getRedisLoginCaptchaExpireMinutes(), TimeUnit.MINUTES);
		// 将key和base64返回给前端
		JSONObject obj = new JSONObject();
		obj.put("key", key);
		return obj;
	}
}
